//
//  ListViewController.swift
//  HyphenateIMDemo
//
//  Created by Shang Hai Rui Xi on 2018/12/29.
//  Copyright © 2018 Shang Hai Rui Xi. All rights reserved.
//

import UIKit

class ListViewController: EaseConversationListViewController {
    
    public var conversationsArray: [EMConversation] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.refreshAndSortView()
        self.tableViewDidTriggerHeaderRefresh()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.delegate = self;
        self.dataSource = self;
        self.removeEmptyConversationsFromDB()
    }
    
    func removeEmptyConversationsFromDB() {
        guard let conversations = EMClient.shared()?.chatManager.getAllConversations() as? [EMConversation] else {
            return
        }
        var needRemoveConversations: [EMConversation] = []
        for co in conversations {
            if (co.latestMessage != nil) || co.type == EMConversationTypeChatRoom {
                needRemoveConversations.append(co)
            }
        }
        if needRemoveConversations.count > 0 {
            EMClient.shared()?.chatManager.deleteConversations(needRemoveConversations, isDeleteMessages: true, completion: nil)
        }
    }
    
    func deleteCellAction(aIndexPath: IndexPath) {
        guard let model = self.dataArray.object(at: aIndexPath.row) as? EaseConversationModel else {
            return
        }
        EMClient.shared()?.chatManager.deleteConversation(model.conversation.conversationId, isDeleteMessages: true, completion: nil)
        self.dataArray.removeObject(at: aIndexPath.row)
        self.tableView.deleteRows(at: [aIndexPath], with: .fade)
    }
}

extension ListViewController: EaseConversationListViewControllerDelegate, EaseConversationListViewControllerDataSource {
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, didSelect conversationModel: IConversationModel!) {
        if (conversationModel != nil) {
            guard let conversation = conversationModel.conversation else { return }
            let chatVc = ChatViewController.init(conversation: conversation)
            chatVc.title = conversationModel.title
            chatVc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(chatVc, animated: true)
            NotificationCenter.default.post(name: NSNotification.Name.init("setupUnreadMessageCount"), object: nil)
            tableView.reloadData()
        }
    }
    
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, modelFor conversation: EMConversation!) -> IConversationModel! {

        let model = EaseConversationModel.init(conversation: conversation)
        if model?.conversation.type == EMConversationTypeChat {
            //要显示用户名和头像
        }
        
        return model
    }
    
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, latestMessageTimeFor conversationModel: IConversationModel!) -> String! {
        var latestMessageTime = ""
        guard let lastMessage = conversationModel.conversation.latestMessage else {
            return ""
        }
        latestMessageTime = NSDate.formattedTime(fromTimeInterval: lastMessage.timestamp)
        return latestMessageTime
    }
    
    func conversationListViewController(_ conversationListViewController: EaseConversationListViewController!, latestMessageTitleFor conversationModel: IConversationModel!) -> NSAttributedString! {
        var attributedStr = NSMutableAttributedString.init()
        var latestMessageTitle = ""
        guard let lastMessage = conversationModel.conversation.latestMessage else {
            return attributedStr
        }
        switch lastMessage.body.type {
        case EMMessageBodyTypeImage:
            latestMessageTitle = "图片"
        case EMMessageBodyTypeText:
            let didReceiveText = EaseConvertToCommonEmoticonsHelper.convert(toCommonEmoticons: (lastMessage.body as? EMTextMessageBody)?.text)
            latestMessageTitle = didReceiveText ?? ""
            if lastMessage.ext?[MESSAGE_ATTR_IS_BIG_EXPRESSION] != nil {
                latestMessageTitle = "动画表情"
            }
        case EMMessageBodyTypeVoice:
            latestMessageTitle = "语音"
        case EMMessageBodyTypeLocation:
            latestMessageTitle = "位置"
        case EMMessageBodyTypeVideo:
            latestMessageTitle = "视频"
        case EMMessageBodyTypeFile:
            latestMessageTitle = "文件"
        default:
            break
        }
        
        attributedStr = NSMutableAttributedString.init(string: latestMessageTitle)
        
        return attributedStr
    }
}
